package com.leyou.cart.service;

import com.leyou.cart.pojo.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartService {
    public static final String KEY_PREFIX = "ly:cart:uid:";
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void addCart(Cart cart) {
        // 获取当前登录用户
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        // 获取hash操作对象，并绑定用户id
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 获取商品id，作为hashKey
        String hashKey = cart.getSkuId().toString();
        // 获取数量
        Integer num = cart.getNum();

        // 获取redis的购物车商品
        Boolean bool = hashOps.hasKey(hashKey);
        // 判断要添加的商品是否存在
        if (bool != null && bool) {
            // 商品存在，修改商品的数量
            cart = JsonUtils.toBean(hashOps.get(hashKey), Cart.class);
            cart.setNum(num + cart.getNum());
        }
        // 写入redis
        hashOps.put(hashKey, JsonUtils.toString(cart));
    }

    public List<Cart> queryCartList() {
        // 获取当前登录用户
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        // 判断购物车是否存在
        Boolean bool = redisTemplate.hasKey(key);
        // 不存在，直接返回
        if (bool == null || !bool) throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        // 获取hash操作对象，并绑定用户id
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 判断是否有数据
        Long size = hashOps.size();
        // 没有数据
        if (size == null || size < 0) throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        // 获取所有value
        List<String> carts = hashOps.values();
        // 返回购物车数据
        return carts.stream().map(json -> JsonUtils.toBean(json, Cart.class)).collect(Collectors.toList());
    }

    public void deleteCart(String skuId) {
        // 获取登录用户
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        redisTemplate.opsForHash().delete(key, skuId);
    }

    public void updateCart(String skuId, Integer num) {
        // 获取登录用户
        String key = KEY_PREFIX + UserHolder.getUser().getId();
        // 获取hash操作对象，并绑定用户id
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 获取redis的购物车商品
        Boolean bool = hashOps.hasKey(skuId);
        // 判断要添加的商品是否存在
        if (bool == null && !bool) {
            log.error("购物车商品不存在，用户：{}, 商品：{}", key, skuId);
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }

        // 获取购物车商品
        log.info("根据skuId查询商品：{}",hashOps.get(skuId));
        Cart cart = JsonUtils.toBean(hashOps.get(skuId), Cart.class);
        // 修改数量
        cart.setNum(num);
        // 写回redis
        hashOps.put(skuId, JsonUtils.toString(cart));
    }
}
